<?php

namespace app\merchant\controller;

use app\merchant\model\BankCard;
use app\merchant\model\MerchantConfig;
use app\merchant\model\TpAssetsPool;
use app\merchant\model\UserCompany;
use app\common\lib\MyController;
use app\common\lib\Page;
use app\merchant\model\TpCredit;
use app\merchant\model\BorrowRequest;
use app\common\lib\Constant;
use app\merchant\model\TpMerchant;
use app\merchant\model\TpAssets;
use app\merchant\model\TpActualInvestRepay;

/**
 * 资产管理
 */
class Management extends MyController
{

    /**
     * 统计车贷，消费金融，其他类的数量
     * @param type $user_id 商户id
     * @return type
     */
    private function _statisticsType($user_id)
    {
        //需要判断商户有哪些类型的贷款，默认展示已有类型的贷款
        $show_type = TpMerchant::where('user_id', '=', $user_id)->value('show_type');
        $categorys = explode(',', $show_type);
        //1车贷2消费贷3企业贷'
        $type_car = $type_consume = $type_enterprise = 0;
        if (in_array(TpAssets::TYPE_CAR, $categorys)) { //车贷
            $type_car = 1;
        }
        if (in_array(TpAssets::TYPE_CONSUME, $categorys)) { //消费贷
            $type_consume = 1;
        }
        if (in_array(TpAssets::TYPE_ENTERPRISE, $categorys)) { //企业贷
            $type_enterprise = 1;
        }
        //公共数据
        $this->assign('type_car', $type_car);
        $this->assign('type_consume', $type_consume);
        $this->assign('type_enterprise', $type_enterprise);

        //车贷数量
        $num_car = $num_consume = $num_enterprise = 0;
        if ($type_car) {
            $num_car = $this->_getNumByType($user_id, TpAssets::TYPE_CAR);
            $this->assign('num_car', $num_car);
        }
        //消费贷数量
        if ($type_consume) {
            $num_consume = $this->_getNumByType($user_id, TpAssets::TYPE_CONSUME);
            $this->assign('num_consume', $num_consume);
        }
        //企业贷数量
        if ($type_enterprise) {
            $num_enterprise = $this->_getNumByType($user_id, TpAssets::TYPE_ENTERPRISE);
            $this->assign('num_enterprise', $num_enterprise);
        }

        return [
            'type_car' => $type_car,
            'type_consume' => $type_consume,
            'type_enterprise' => $type_enterprise,
        ];
    }

    /**
     * 根据商户id和资产类型获取资产数量
     * @param type $user_id 商户id
     * @param type $type 资产类型
     * @return type int 数量
     */
    private function _getNumByType($user_id, $type)
    {
        $num = TpAssetsPool::alias('ap')
                ->join('tp_borrow_request br', 'ap.request_id = br.id')
                ->where('ap.merchant', '=', $user_id)
                ->where('br.type', '=', $type)
                ->count('ap.id');
        return $num;
    }

    /**
     * 统计不同展业的不同状态的数量
     * @param type $user_id 商户id
     * @param type $type 展业类型
     * @return type
     */
    private function _statisticsStatus($user_id, $type)
    {
        //全部
        $all = $this->_getNumByStatus($user_id, $type);
        //未售
        $status_0 = $this->_getNumByStatus($user_id, $type, TpAssetsPool::STATUS_UNSOLD);
        //募集中
        $status_1 = $this->_getNumByStatus($user_id, $type, TpAssetsPool::STATUS_RAISING);
        //还款中
        $status_2 = $this->_getNumByStatus($user_id, $type, TpAssetsPool::STATUS_PAYING);
        //已还款
        $status_3 = $this->_getNumByStatus($user_id, $type, TpAssetsPool::STATUS_PAID);

        $this->assign('all', $all);
        $this->assign('status_0', $status_0);
        $this->assign('status_1', $status_1);
        $this->assign('status_2', $status_2);
        $this->assign('status_3', $status_3);

        return TRUE;
    }

    /**
     * 根据类型，状态获取资产数量
     * @param type $user_id 商户id
     * @param type $type 类型
     * @param type $status 状态 -1为默认，表示获取全部状态
     * @return type int 数量
     */
    private function _getNumByStatus($user_id, $type, $status = -1)
    {
        if ($status == -1) {
            $num = TpAssetsPool::alias('ap')
                    ->join('tp_borrow_request br', 'ap.request_id = br.id')
                    ->where('ap.merchant', '=', $user_id)
                    ->where('br.type', '=', $type)
                    ->count('ap.id');
        } else {
            $num = TpAssetsPool::alias('ap')
                    ->join('tp_borrow_request br', 'ap.request_id = br.id')
                    ->where('ap.merchant', '=', $user_id)
                    ->where('ap.status', '=', $status)
                    ->where('br.type', '=', $type)
                    ->count('ap.id');
        }

        return $num;
    }

    /**
     * 搜索条件和表单数据
     * @param type $user_id
     * @param type $type
     * @return boolean
     */
    private function _statisticsData($user_id, $type)
    {
        //搜索条件
        $batch_number = input('batch_number/s', '');
        $real_name = input('real_name/s', '');
        $user_phone = input('user_phone/s', '');
        $idcard = input('idcard/s', '');
        $update_time_start = input('update_time_start/s', '');
        $update_time_end = input('update_time_end/s', '');
        $left_duration = input('left_duration/d', '');
        $status = input('status', 'all');

        $company_name = input('company_name', '');
        $telephone = input('telephone', '');

        $this->assign('batch_number', $batch_number);
        $this->assign('real_name', $real_name);
        $this->assign('user_phone', $user_phone);
        $this->assign('idcard', $idcard);
        $this->assign('update_time_start', $update_time_start);
        $this->assign('update_time_end', $update_time_end);
        $this->assign('left_duration', $left_duration);
        $this->assign('status', $status);

        $this->assign('company_name', $company_name);
        $this->assign('telephone', $telephone);

        //查找数据
        $where['ap.merchant'] = ['=', $user_id];
        $where_more['br.type'] = ['=', $type]; //区间查询，不能都用$where，不然就替换了

        if ($status != 'all') {
            $where['ap.status'] = ['=', $status];
        }
        if ($batch_number) {
            $where['ap.batch_number'] = ['=', $batch_number];
        }
        if ($real_name) {
            $where['tu.real_name'] = ['like', '%' . $real_name . '%'];
        }
        if ($user_phone) {
            $where['tu.user_phone'] = ['=', $user_phone];
        }
        if ($idcard) {
            $where['tu.idcard'] = ['=', $idcard];
        }
        if ($update_time_start) {
            $where['ap.update_time'] = ['>=', strtotime($update_time_start)];
        }
        if ($update_time_end) {
            $where_more['ap.update_time'] = ['<', strtotime($update_time_end) + 24 * 3600];
        }
        if ($left_duration) {
            if ($left_duration == 1) {
                $where['(br.duration - br.sold_duration)'] = ['<=', 60];
            } elseif ($left_duration == 2) {
                $where['(br.duration - br.sold_duration)'] = ['<=', 150];
                $where_more['(br.duration - br.sold_duration)'] = ['>', 60];
            } elseif ($left_duration == 3) {
                $where['(br.duration - br.sold_duration)'] = ['<=', 300];
                $where_more['(br.duration - br.sold_duration)'] = ['>', 150];
            } elseif ($left_duration == 4) {
                $where['(br.duration - br.sold_duration)'] = ['>', 300];
            }
        }

        if ($company_name) {
            $where['uc.company_name'] = ['like', '%' . $company_name . '%'];
        }
        if ($telephone) {
            $where['uc.telephone'] = ['=', $telephone];
        }

        //数据
        $page = input('page', 1);
        $count = TpAssetsPool::alias('ap')
                ->join('tp_borrow_request br', 'ap.request_id = br.id')
                ->join('tp_user tu', 'ap.borrower_uid = tu.uid')
                ->join('tp_user_company uc', 'ap.borrower_uid = uc.user_id', 'LEFT')
                ->where($where)
                ->where($where_more)
                ->count('ap.id');
        $field = 'ap.*, tu.real_name, tu.user_phone, tu.idcard, ta.borrow_money, br.duration as duration_all, br.sold_duration, br.money, uc.company_name, uc.telephone, brd.extra_filed';
        $list = TpAssetsPool::alias('ap')
                ->join('tp_borrow_request br', 'ap.request_id = br.id')
                ->join('tp_user tu', 'ap.borrower_uid = tu.uid')
                ->join('tp_borrow_request_detail brd', 'ap.request_id = brd.borrow_request_id', 'LEFT')
                ->join('tp_account ta', 'ap.borrower_uid = ta.user_id', 'LEFT')
                ->join('tp_user_company uc', 'ap.borrower_uid = uc.user_id', 'LEFT')
                ->where($where)
                ->where($where_more)
                ->page($page, Constant::PAGE_SIZE_MIN)
                ->field($field)
                ->select();
        //在贷余额
        $money_max = 0;
        if ($type == TpAssets::TYPE_CAR || $type == TpAssets::TYPE_CONSUME) {
            $money_max = Constant::INDIVIDUAL_MONEY_MAX;
        } else {
            $money_max = Constant::ENTERPRISE_MONEY_MAX;
        }

        foreach ($list as $key => $val) {
            $list[$key]['left_money'] = number_format($money_max - $val['borrow_money'], 2); //在贷余额
            $list[$key]['left_duration'] = $val['duration_all'] - $val['sold_duration']; //剩余期限
            $list[$key]['repayment_type'] = TpAssets::getRepaymentTypeName($val['repayment_type']); //还款方式
            $list[$key]['status'] = TpAssetsPool::getStatusName($val['status']); //状态
            
            $extra_filed = json_decode($val['extra_filed'], TRUE);
            //数据结构修改了，做法也得修改 2018-05-10
            $items = [];
            foreach ($extra_filed as $extra_val) {
                foreach ($extra_val['items'] as $value) {
                    $items[$value['field']] = $value['value'];
                }
            }
            if ($type == TpAssets::TYPE_CAR) { //车辆评估值
                //$extra_filed = json_decode($val['extra_filed'], TRUE);
                //$list[$key]['car_price'] = isset($extra_filed['car_price']) ? $extra_filed['car_price'] : '';
                $list[$key]['car_price'] = isset($items['car_price']) ? $items['car_price'] : '';
            } elseif ($type == TpAssets::TYPE_CONSUME) { //常用联系人
                //$extra_filed = json_decode($val['extra_filed'], TRUE);
                //$list[$key]['contacts'] = isset($extra_filed['contacts']) ? $extra_filed['contacts'] : '';
                $list[$key]['contacts'] = isset($items['contacts']) ? $items['contacts'] : '';
            }
        }
        $this->assign('list', $list);

        //分页
        $page_class = new Page();
        //$paginator = $page_class->pages($count, Constant::PAGE_SIZE_MIN, $page);
        $paginator = $page_class->ajaxPages($count, Constant::PAGE_SIZE_MIN, $page);//ajax
        $this->assign('paginator', $paginator);

        return TRUE;
    }
    
    /**
     * 搜索条件和表单数据 ajax
     * @param type $user_id
     * @param type $type
     * @param type $url
     * @return type
     */
    private function _statisticsDataAjax($user_id, $type, $url)
    {
        //搜索条件
        $batch_number = input('batch_number/s', '');
        $real_name = input('real_name/s', '');
        $user_phone = input('user_phone/s', '');
        $idcard = input('idcard/s', '');
        $update_time_start = input('update_time_start/s', '');
        $update_time_end = input('update_time_end/s', '');
        $left_duration = input('left_duration/d', '');
        $status = input('status', 'all');
        $company_name = input('company_name', '');
        $telephone = input('telephone', '');
        /*
        $this->assign('batch_number', $batch_number);
        $this->assign('real_name', $real_name);
        $this->assign('user_phone', $user_phone);
        $this->assign('idcard', $idcard);
        $this->assign('update_time_start', $update_time_start);
        $this->assign('update_time_end', $update_time_end);
        $this->assign('left_duration', $left_duration);
        $this->assign('status', $status);
        $this->assign('company_name', $company_name);
        $this->assign('telephone', $telephone);
        */
        //查找数据
        $where['ap.merchant'] = ['=', $user_id];
        $where_more['br.type'] = ['=', $type]; //区间查询，不能都用$where，不然就替换了

        if ($status != 'all') {
            $where['ap.status'] = ['=', $status];
        }
        if ($batch_number) {
            $where['ap.batch_number'] = ['=', $batch_number];
        }
        if ($real_name) {
            $where['tu.real_name'] = ['like', '%' . $real_name . '%'];
        }
        if ($user_phone) {
            $where['tu.user_phone'] = ['=', $user_phone];
        }
        if ($idcard) {
            $where['tu.idcard'] = ['=', $idcard];
        }
        if ($update_time_start) {
            $where['ap.update_time'] = ['>=', strtotime($update_time_start)];
        }
        if ($update_time_end) {
            $where_more['ap.update_time'] = ['<', strtotime($update_time_end) + 24 * 3600];
        }
        if ($left_duration) {
            if ($left_duration == 1) {
                $where['(br.duration - br.sold_duration)'] = ['<=', 60];
            } elseif ($left_duration == 2) {
                $where['(br.duration - br.sold_duration)'] = ['<=', 150];
                $where_more['(br.duration - br.sold_duration)'] = ['>', 60];
            } elseif ($left_duration == 3) {
                $where['(br.duration - br.sold_duration)'] = ['<=', 300];
                $where_more['(br.duration - br.sold_duration)'] = ['>', 150];
            } elseif ($left_duration == 4) {
                $where['(br.duration - br.sold_duration)'] = ['>', 300];
            }
        }

        if ($company_name) {
            $where['uc.company_name'] = ['like', '%' . $company_name . '%'];
        }
        if ($telephone) {
            $where['uc.telephone'] = ['=', $telephone];
        }

        //数据
        $page = input('page_ajax', 1);
        $count = TpAssetsPool::alias('ap')
                ->join('tp_borrow_request br', 'ap.request_id = br.id')
                ->join('tp_user tu', 'ap.borrower_uid = tu.uid')
                ->join('tp_user_company uc', 'ap.borrower_uid = uc.user_id', 'LEFT')
                ->where($where)
                ->where($where_more)
                ->count('ap.id');
        $field = 'ap.*, tu.real_name, tu.user_phone, tu.idcard, ta.borrow_money, br.duration as duration_all, br.sold_duration, br.money, uc.company_name, uc.telephone, brd.extra_filed';
        $list = TpAssetsPool::alias('ap')
                ->join('tp_borrow_request br', 'ap.request_id = br.id')
                ->join('tp_user tu', 'ap.borrower_uid = tu.uid')
                ->join('tp_borrow_request_detail brd', 'ap.request_id = brd.borrow_request_id', 'LEFT')
                ->join('tp_account ta', 'ap.borrower_uid = ta.user_id', 'LEFT')
                ->join('tp_user_company uc', 'ap.borrower_uid = uc.user_id', 'LEFT')
                ->where($where)
                ->where($where_more)
                ->page($page, Constant::PAGE_SIZE_MIN)
                ->field($field)
                ->select();
        //在贷余额
        $money_max = 0;
        if ($type == TpAssets::TYPE_CAR || $type == TpAssets::TYPE_CONSUME) {
            $money_max = Constant::INDIVIDUAL_MONEY_MAX;
        } else {
            $money_max = Constant::ENTERPRISE_MONEY_MAX;
        }

        foreach ($list as $key => $val) {
            $list[$key]['left_money'] = number_format($money_max - $val['borrow_money'], 2); //在贷余额
            $list[$key]['left_duration'] = $val['duration_all'] - $val['sold_duration']; //剩余期限
            $list[$key]['repayment_type'] = TpAssets::getRepaymentTypeName($val['repayment_type']); //还款方式
            $list[$key]['status'] = TpAssetsPool::getStatusName($val['status']); //状态
            
            $extra_filed = json_decode($val['extra_filed'], TRUE);
            //数据结构修改了，做法也得修改 2018-05-10
            $items = [];
            foreach ($extra_filed as $extra_val) {
                foreach ($extra_val['items'] as $value) {
                    $items[$value['field']] = $value['value'];
                }
            }
            if ($type == TpAssets::TYPE_CAR) { //车辆评估值
                //$extra_filed = json_decode($val['extra_filed'], TRUE);
                //$list[$key]['car_price'] = isset($extra_filed['car_price']) ? $extra_filed['car_price'] : '';
                $list[$key]['car_price'] = isset($items['car_price']) ? $items['car_price'] : '';
            } elseif ($type == TpAssets::TYPE_CONSUME) { //常用联系人
                //$extra_filed = json_decode($val['extra_filed'], TRUE);
                //$list[$key]['contacts'] = isset($extra_filed['contacts']) ? $extra_filed['contacts'] : '';
                $list[$key]['contacts'] = isset($items['contacts']) ? $items['contacts'] : '';
            }
        }
        //$this->assign('list', $list);

        //分页
        $page_class = new Page();
        $page_list = $page_class->ajaxPages($count, Constant::PAGE_SIZE_MIN, $page);//ajax
        /*
        $paginator = $page_class->pages($count, Constant::PAGE_SIZE_MIN, $page);
        $this->assign('paginator', $paginator);
        return [
            'page_ajax' => $page,
            "$paginator" => $paginator,
            "$list" => $list
        ];
        */

        $html = $this->fetch($url, [
            'page_ajax' => $page,
            'list' => $list,
        ]);
        return [
            'html' => $html,
            'page_list' => $page_list,
            'status' => $status
        ];
    }

    /**
     * 借款管理-首次打开
     * @return type
     */
    public function index()
    {
        $user_id = $this->_Uid;

        //调用公共方法
        $type_list = $this->_statisticsType($user_id); //展业
        $type = 0;
        if ($type_list['type_car']) { //车贷
            $type = TpAssets::TYPE_CAR;
        } elseif ($type_list['type_consume']) { //消费贷
            $type = TpAssets::TYPE_CONSUME;
        } elseif ($type_list['type_enterprise']) { //企业贷
            $type = TpAssets::TYPE_ENTERPRISE;
        } else {
            return '当前商户没有展业';
        }
        $this->assign('type', $type);

        $status_list = $this->_statisticsStatus($user_id, $type); //状态

        $data_list = $this->_statisticsData($user_id, $type); //搜索条件和表单数据

        if ($type == TpAssets::TYPE_CAR) { //车贷
            return view('Management/car');
        } elseif ($type == TpAssets::TYPE_CONSUME) { //消费贷
            return view('Management/consume');
        } elseif ($type == TpAssets::TYPE_ENTERPRISE) { //企业贷
            return view('Management/enterprise');
        } else {
            return '当前商户没有展业';
        }
    }

    /**
     * 车贷
     * @return type
     */
    public function car()
    {
        $user_id = $this->_Uid;
        $type = input('type', TpAssets::TYPE_CAR);
        $this->assign('type', $type);

        //调用公共方法
        $type_list = $this->_statisticsType($user_id); //展业
        $status_list = $this->_statisticsStatus($user_id, $type); //状态
        $data_list = $this->_statisticsData($user_id, $type); //搜索条件和表单数据

        return view('Management/car');
    }
    
    /**
     * 车贷分页
     * @return type
     */
    public function carAjax()
    {
        $user_id = $this->_Uid;
        $type = input('type/d', TpAssets::TYPE_CAR);
        
        $data_list = $this->_statisticsDataAjax($user_id, $type, 'Management/car_listcontent');
        
        return [
            'code' => 0,
            'data' => [
                'html' => $data_list['html'],
                'page_list' => $data_list['page_list'],
                'status' => $data_list['status'],
                'type' => $type
            ]
        ];
    }

    /**
     * 消费贷
     * @return type
     */
    public function consume()
    {
        $user_id = $this->_Uid;
        $type = input('type', TpAssets::TYPE_CONSUME);
        $this->assign('type', $type);

        //调用公共方法
        $type_list = $this->_statisticsType($user_id); //展业
        $status_list = $this->_statisticsStatus($user_id, $type); //状态
        $data_list = $this->_statisticsData($user_id, $type); //搜索条件和表单数据        

        return view('Management/consume');
    }
    
    /**
     * 消费贷 ajax
     * @return type
     */
    public function consumeAjax()
    {
        $user_id = $this->_Uid;
        $type = input('type/d', TpAssets::TYPE_CONSUME);
        
        $data_list = $this->_statisticsDataAjax($user_id, $type, 'Management/consume_listcontent');
        
        return [
            'code' => 0,
            'data' => [
                'html' => $data_list['html'],
                'page_list' => $data_list['page_list'],
                'status' => $data_list['status'],
                'type' => $type
            ]
        ];
    }

    /**
     * 企业贷
     * @return type
     */
    public function enterprise()
    {
        $user_id = $this->_Uid;
        $type = input('type', TpAssets::TYPE_ENTERPRISE);
        $this->assign('type', $type);

        //调用公共方法
        $type_list = $this->_statisticsType($user_id); //展业
        $status_list = $this->_statisticsStatus($user_id, $type); //状态
        $data_list = $this->_statisticsData($user_id, $type); //搜索条件和表单数据

        return view('Management/enterprise');
    }
    
    /**
     * 企业贷 ajax
     * @return type
     */
    public function enterpriseAjax()
    {
        $user_id = $this->_Uid;
        $type = input('type', TpAssets::TYPE_ENTERPRISE);
        
        $data_list = $this->_statisticsDataAjax($user_id, $type, 'Management/enterprise_listcontent');
        
        return [
            'code' => 0,
            'data' => [
                'html' => $data_list['html'],
                'page_list' => $data_list['page_list'],
                'status' => $data_list['status'],
                'type' => $type
            ]
        ];
    }

    /**
     * 获取可以下载的文件资料
     * @param type $type 展业类型
     * @param type $extra_filed 扩展字段数组
     * @return boolean
     */
    private function _getFile($type, $extra_filed)
    {
        //动态获取字段，要从配置里面读取
        $fields = BorrowRequest::getExcelFiledMap($type);
        $fields = $fields['json_map'];
        $files = []; //可以下载的文件
        $upaiyun = config('upyun_config.upaiyun') . '/'; //基础路径
        foreach ($fields as $key => $val) {
            if (isset($val['field_type']) && $val['field_type'] == 'file_url') {
                //获取字段名
                $field = $val['field'];
                //判断是否有此字段，并且此字段是有值
                if (isset($extra_filed[$field]) && $extra_filed[$field]) {
                    $temp = [
                        'title' => $val['title'],
                        'url' => $upaiyun . $extra_filed[$field]
                    ];
                    $files[] = $temp;
                }
            }
        }
        //有值才加载
        if ($files) {
            $this->assign('files', $files);
        }

        return TRUE;
    }

    /**
     * 车贷详情
     * @return type
     */
    public function carDetail()
    {
        $id = input('id/d', 0);
        if ($id === 0) {
            return $this->messageView('id错误');
        }
        $field = 'ap.*, a.code, br.duration as duration_all, br.sold_duration, br.money, br.repayment_source, br.money_use_for, brd.extra_filed, tu.real_name, tu.user_phone, tu.idcard';
        $pool = $this->_getPoolById($id, $field);
        if (!$pool) {
            return $this->messageView('无此资产详情');
        }

        $extra_filed = json_decode($pool['extra_filed'], TRUE);
        //数据结构修改了，做法也得修改 2018-05-10
        $items = [];
        foreach ($extra_filed as $val) {
            foreach ($val['items'] as $value) {
                $items[$value['field']] = $value['value'];
            }
        }

        //获取可以下载的文件资料
        $this->_getFile(TpAssets::TYPE_CAR, $items);

        $pool['car_num'] = isset($items['car_num']) ? $items['car_num'] : '';
        $pool['car_type'] = isset($items['car_type']) ? $items['car_type'] : '';
        $pool['car_price'] = isset($items['car_price']) ? $items['car_price'] : '';
        $pool['percent'] = isset($items['percent']) ? $items['percent'] : '';
        $pool['location'] = isset($items['location']) ? $items['location'] : '';
        $pool['address'] = isset($items['address']) ? $items['address'] : '';
        $pool['contacts'] = isset($items['contacts']) ? $items['contacts'] : '';
        $pool['company_name'] = isset($items['company_name']) ? $items['company_name'] : '';
        $pool['industry'] = isset($items['industry']) ? $items['industry'] : '';

        $pool['left_duration'] = $pool['duration_all'] - $pool['sold_duration'];
        $pool['repayment_type'] = TpAssets::getRepaymentTypeName($pool['repayment_type']); //还款方式
        $pool['status_name'] = TpAssetsPool::getStatusName($pool['status']); //状态

        if (in_array($pool['status'], [TpAssetsPool::STATUS_PAYING, TpAssetsPool::STATUS_PAID])) {
            $pool['pay_money'] = $pool['amount'] + $pool['interest_rate']; //本息
            //统计已还金额和剩余应还金额
            $payed = $this->_getMoneyByStatus($pool['id'], [TpActualInvestRepay::STATUS_PAIED, TpActualInvestRepay::STATUS_BEFORE]);
            $pool['payed'] = $payed;
            $pool['need_pay'] = $pool['pay_money'] - $payed;
        }

        $this->assign('pool', $pool);

        return view('Management/car_detail');
    }

    /**
     * 消费贷详情
     * @return type
     */
    public function consumeDetail()
    {
        $id = input('id/d', 0);
        if ($id === 0) {
            return $this->messageView('id错误');
        }
        $field = 'ap.*, a.code, br.duration as duration_all, br.sold_duration, br.money, br.repayment_source, br.money_use_for, brd.extra_filed, tu.real_name, tu.user_phone, tu.idcard';
        $pool = $this->_getPoolById($id, $field);
        if (!$pool) {
            return $this->messageView('无此资产详情');
        }

        $extra_filed = json_decode($pool['extra_filed'], TRUE);
        //数据结构修改了，做法也得修改 2018-05-10
        $items = [];
        foreach ($extra_filed as $val) {
            foreach ($val['items'] as $value) {
                $items[$value['field']] = $value['value'];
            }
        }

        //获取可以下载的文件资料
        $this->_getFile(TpAssets::TYPE_CONSUME, $items);

        $pool['location'] = isset($items['location']) ? $items['location'] : '';
        $pool['address'] = isset($items['address']) ? $items['address'] : '';
        $pool['contacts'] = isset($items['contacts']) ? $items['contacts'] : '';
        $pool['company_name'] = isset($items['company_name']) ? $items['company_name'] : '';
        $pool['industry'] = isset($items['industry']) ? $items['industry'] : '';

        $pool['repayment_type'] = TpAssets::getRepaymentTypeName($pool['repayment_type']); //还款方式
        $pool['status_name'] = TpAssetsPool::getStatusName($pool['status']); //状态

        if (in_array($pool['status'], [TpAssetsPool::STATUS_PAYING, TpAssetsPool::STATUS_PAID])) {
            $pool['pay_money'] = $pool['amount'] + $pool['interest_rate']; //本息
            //统计已还金额和剩余应还金额
            $payed = $this->_getMoneyByStatus($pool['id'], [TpActualInvestRepay::STATUS_PAIED, TpActualInvestRepay::STATUS_BEFORE]);
            $pool['payed'] = $payed;
            $pool['need_pay'] = $pool['pay_money'] - $payed;
        }

        $this->assign('pool', $pool);

        return view('Management/consume_detail');
    }

    /**
     * 企业贷详情
     * @return type
     */
    public function enterpriseDetail()
    {
        $id = input('id/d', 0);
        if ($id === 0) {
            return $this->messageView('id错误');
        }
        //借款信息
        $field = 'ap.*, a.code, br.duration as duration_all, br.sold_duration, br.money, br.repayment_source, br.money_use_for, brd.extra_filed';
        $pool = $this->_getPoolById($id, $field, 1);
        if (!$pool) {
            return $this->messageView('无此资产详情');
        }

        $extra_filed = json_decode($pool['extra_filed'], TRUE);
        //数据结构修改了，做法也得修改 2018-05-10
        $items = [];
        foreach ($extra_filed as $val) {
            foreach ($val['items'] as $value) {
                $items[$value['field']] = $value['value'];
            }
        }

        //获取可以下载的文件资料
        $this->_getFile(TpAssets::TYPE_ENTERPRISE, $items);

        $pool['left_duration'] = $pool['duration_all'] - $pool['sold_duration'];
        $pool['repayment_type'] = TpAssets::getRepaymentTypeName($pool['repayment_type']); //还款方式
        $pool['status_name'] = TpAssetsPool::getStatusName($pool['status']); //状态

        if (in_array($pool['status'], [TpAssetsPool::STATUS_PAYING, TpAssetsPool::STATUS_PAID])) {
            $pool['pay_money'] = $pool['amount'] + $pool['interest_rate']; //本息
            //统计已还金额和剩余应还金额
            $payed = $this->_getMoneyByStatus($pool['id'], [TpActualInvestRepay::STATUS_PAIED, TpActualInvestRepay::STATUS_BEFORE]);
            $pool['payed'] = $payed;
            $pool['need_pay'] = $pool['pay_money'] - $payed;
        }

        $this->assign('pool', $pool);

        //用户信息
        $company = UserCompany::where('user_id', '=', $pool['borrower_uid'])->find();
        $company['bank_code'] = config('bank_list.' . $company['bank_code']); //银行信息
        $this->assign('company', $company);

        return view('Management/enterprise_detail');
    }
    
    /**
     * 获取资产详情共用方法
     * @param type $id
     * @param type $field
     * @param type $is_enterprise int 1为企业贷
     * @return type
     */
    private function _getPoolById($id, $field, $is_enterprise = 0)
    {
        if ($is_enterprise == 1) {
            $pool = TpAssetsPool::alias('ap')
                ->join('tp_borrow_request br', 'ap.request_id = br.id')
                ->join('tp_borrow_request_detail brd', 'ap.request_id = brd.borrow_request_id', 'LEFT')
                ->join('tp_assets a', 'ap.assets_id = a.id')
                ->where('ap.id', '=', $id)
                ->field($field)
                ->find();
        } else {
            $pool = TpAssetsPool::alias('ap')
                ->join('tp_borrow_request br', 'ap.request_id = br.id')
                ->join('tp_borrow_request_detail brd', 'ap.request_id = brd.borrow_request_id', 'LEFT')
                ->join('tp_assets a', 'ap.assets_id = a.id')
                ->join('tp_user tu', 'ap.borrower_uid = tu.uid')
                ->where('ap.id', '=', $id)
                ->field($field)
                ->find();
        }
        
        return $pool;
    }

    /**
     * 根据资产id和状态获取金额
     * @param type $id 资产id
     * @param type $status array 状态
     * @return type 钱
     */
    private function _getMoneyByStatus($id, $status)
    {
        $money = TpCredit::alias('c')
                ->join('tp_actual_invest_repay ir', 'c.id = ir.actual_invest_id')
                ->where('c.assets_pool_id', '=', $id)
                ->where('ir.status', 'in', $status)
                ->sum('ir.capital + ir.interest');
        return $money;
    }

    /**
     * 投资明细
     * @return type
     */
    public function investDetail()
    {
        $page = input('page', 1);
        $where['tc.assets_pool_id'] = ['=', input('id')];
        $count = TpCredit::alias('tc')
                ->join('tp_user tu', 'tc.investor_uid = tu.uid')
                ->where($where)
                ->count('tc.id');
        $list = TpCredit::alias('tc')
                ->join('tp_user tu', 'tc.investor_uid = tu.uid')
                ->where($where)
                ->page($page, Constant::PAGE_SIZE_MIN)
                ->field('tu.real_name, tu.user_phone, tc.money, tc.create_time')
                ->select();

        $this->assign('list', $list);

        //分页
        $page_class = new Page();
        $paginator = $page_class->pages($count, Constant::PAGE_SIZE_MIN, $page);
        $this->assign('paginator', $paginator);

        return view('Management/invest_detail');
    }

}
